#!/bin/python

import os
import sys
import json
import platform
import subprocess

try:
    team = str(json.load(open(".wpilib/wpilib_preferences.json"))['teamNumber'])
    build_type = sys.argv[1]
    program = "output/RoboRIO/%s/bin/FRCUserProgram" % build_type
    robot_ip = None
except IndexError:
    print("Arguments: <Debug | Release>")
    os.error("Not enough parameters passed!")

if not os.path.isfile(program):
    os.error("Unable to file user program, did you compile?")

if len(team) == 4:
    robot_ip="10.%s.%s.2" % (team[:1], team[1:])
elif len(team) == 3:
    robot_ip="10.%s.%s.2" % (team[:0], team[0:])
else:
    os.error("Unable to determain robot ip from team number")

def deploy_mdns():
    os.system("ssh 'lvuser@roboRIO-%s-FRC.local' 'killall -9 FRCUserProgram && rm ~/FRCUserProgram && exit'" % team)
    os.system("scp '%s/FRCUserProgram' 'lvuser@roboRIO-%s-FRC.local:~/FRCUserProgram'" % (output_dir, team))

def deploy_usb():
    os.system("ssh 'lvuser@172.22.11.2' 'killall -9 FRCUserProgram && rm ~/FRCUserProgram && exit'")
    os.system("scp '%s/FRCUserProgram' 'lvuser@172.22.11.2:~/FRCUserProgram'" % output_dir)

def deploy_ethernet():
    os.system("ssh 'lvuser@%s' 'killall -9 FRCUserProgram && rm ~/FRCUserProgram && exit'" % robot_ip)
    os.system("scp '%s/FRCUserProgram' 'lvuser@%s:~/FRCUserProgram'" % (output_dir, robot_ip))

def ping(host):
    """Returns True if host(str) responds to a ping request."""
    # Option for the number of packets as a function of
    param = '-n' if platform.system().lower()=='windows' else '-c'
    # Building the command. Ex: "ping -c 1 google.com"
    command = ['ping', param, '2', host]
    return subprocess.call(command) == 0

if ping("roboRIO-%s-FRC.local" % team):
    deploy_mdns()
elif ping("172.22.11.2"):
    deploy_usb()
elif ping(robot_ip):
    deploy_ethernet()
else:
    os.error("Deploy failed at all points! Are you connected to the robot?")

print("Succesfully deployed robot program")
